package com.capsulode.excel.conversion.impl;

import com.capsulode.excel.conversion.Converter;
import com.capsulode.excel.exception.CellTypeNotExpectException;
import com.capsulode.excel.exception.ConversionFailException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class StringConverter implements Converter<String> {
    @Override
    public String convert(Cell cell) throws CellTypeNotExpectException {
        if (CellType.STRING.equals(cell.getCellTypeEnum())) {
            String trim = cell.getStringCellValue().trim();
            return trim.isEmpty() ? null : trim;
        }
        if (CellType.BLANK.equals(cell.getCellTypeEnum())) {
            return null;
        }
        if (CellType.BOOLEAN.equals(cell.getCellTypeEnum())) {
            return String.valueOf(cell.getBooleanCellValue());
        }
        if (CellType.NUMERIC.equals(cell.getCellTypeEnum())) {
            return new BigDecimal(cell.getNumericCellValue()).setScale(0, RoundingMode.HALF_UP).toString();
        }

        throw new CellTypeNotExpectException(cell.getRowIndex(), cell.getColumnIndex());
    }

    @Override
    public void serialize(Object value, Cell cell) throws ConversionFailException, CellTypeNotExpectException {
        cell.setCellValue(value.toString());
    }
}
